package com.hisan.freeride.home.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.blankj.utilcode.util.LogUtils;
import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseAppLication;
import com.hisan.freeride.common.base.BaseFragment;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.utils.MyHandlerUtil;
import com.hisan.freeride.common.utils.utils.TokenUtils;
import com.hisan.freeride.common.view.MyLinearLayoutManager;
import com.hisan.freeride.databinding.ReserveFragmentBinding;
import com.hisan.freeride.home.activity.EvaluationActivity;

import com.hisan.freeride.home.adapter.ReserveAdapter;
import com.hisan.freeride.home.model.FReserve;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.ViewStatus;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import java.util.ArrayList;
import java.util.List;


/**
 * 创建时间 : 2017/6/6
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：乘坐行程页面
 */
public class ReserveFragment extends BaseFragment<ReserveFragmentBinding> {
    private ReserveAdapter adapter;
    private int type=1;
    //页数
    private int pageNumber=1;
    //广播
    private InnerBroadcastReceiver receiver;
    //识别弹窗标识
    private int bur=1;
    private FReserve fReserve;
    private List<FReserve> fReserves=new ArrayList<>();

    //统一的Fragment构建方法
    public static ReserveFragment newInstance(int flag) {
        Bundle args = new Bundle();
        //type代表页签，1：进行中 3：成功 2：失败
        args.putInt("type", flag);
        ReserveFragment fragment = new ReserveFragment();
        fragment.setArguments(args);
        return fragment;
    }

    //取消行程
    private void cancel(FReserve homeModel) {
        int id=homeModel.getId();
        Intent intent = new Intent("cancel");
        intent.putExtra("id", id);
        getActivity().sendBroadcast(intent);
    }



    //注册广播接收者
    private void registerReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction("cancel");
        receiver = new InnerBroadcastReceiver();
        getActivity().registerReceiver(receiver,filter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.reserve_fragment;
    }

    @Override
    protected void initView() {
        mBinding.setStateModel(mStateModel);
        adapter=new ReserveAdapter(type,new ArrayList<>(0));
        mBinding.recy.setLayoutManager(new MyLinearLayoutManager(getActivity()));
        mBinding.recy.setAdapter(adapter);
        if (BaseAppLication.getInstance().ispage()){
            registerReceiver();
        }
        Bundle bundle = getArguments();
        if (!CollectionUtils.isNullOrEmpty(bundle)){
            type=bundle.getInt("type");
        }
    }

    @Override
    protected void initEvent() {
        adapter.setButtonClickListener((p, data) -> {
            if (p == 1) {
                bur = 1;
                fReserve = data;
                getmDialog("是否确认取消？", "取消", "确定").show();
            } else if (p == 2) {
                getCdetail(data.getId());
                int id = data.getId();
                Bundle bundle1 = new Bundle();
                bundle1.putInt("id", id);
                startActivityForResult(EvaluationActivity.class, 99, bundle1, true);
            }
        });
        mBinding.pull.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                fReserves.clear();
                pageNumber = 1;
                if (!BaseAppLication.getInstance().ispage())
                    BaseAppLication.getInstance().setIspage(true);
                getData();
                mBinding.pull.finishRefresh();

            }

            @Override
            public void loadMore() {
                pageNumber++;
                if (!BaseAppLication.getInstance().ispage())
                    BaseAppLication.getInstance().setIspage(true);
                getData();
                mBinding.pull.finishLoadMore();
            }
        });
    }
    //获取评价详情
private void getCdetail(int id){
    OkGo.get(AppConfig.Cdetail)
            .tag(this)
            .params("id",id)
            .execute(new DialogCallback<Object>(getActivity()){


            });
}
private void getData(){
    if (BaseAppLication.getInstance().ispage()){
        BaseAppLication.getInstance().setIspage(false);
        OkGo.<List<FReserve>>get(AppConfig.Booking)
                .tag(this)
                .params("page",pageNumber)
                .params("size",20)
                .params("status",type)
                .execute(new DialogCallback<List<FReserve>>(getActivity()) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<List<FReserve>> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)){
                                showData();
                                if (response.body().size()>=20){
                                    mBinding.pull.setCanLoadMore(true);
                                }else {
                                    mBinding.pull.setCanLoadMore(false);
                                }
                                fReserves.addAll(response.body());
                                adapter.setNewData(type,fReserves);
                            }else {
                                showErrorView(response.code());
                            }
                        }else {
                            if (!CollectionUtils.isNullOrEmpty(fReserves))  adapter.setNewData(type,fReserves);
                            else noData();
                        }
                    }
                    @Override
                    public void onError(com.lzy.okgo.model.Response<List<FReserve>> response) {
                        super.onError(response);
                        showErrorView(response.code());
                    }
                });
    }
}
    @Override
    protected void loadData(boolean isRefresh) {
        fReserves.clear();
        getData();
    }

    class InnerBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            int id=intent.getIntExtra("id",-1);
            if ("cancel".equals(action)) {
                String token=TokenUtils.getToken();
                cancel(id,token);
            }
        }
    }

    @Override
    public void onOk() {
        super.onOk();
        if (bur==1){
            cancel(fReserve);
        }
//        else {
//            Delete(fReserve.getId());
//        }
    }

    @Override
    public void onCancel() {
        super.onCancel();
        if (mDialog.isShowing())mDialog.dismiss();
    }

    //取消行程
    private void cancel(int id, String token) {
        HttpParams Params=new HttpParams();
        Params.put("id",id);
        Params.put("type",2);;
        OkGo.put(AppConfig.Tripcancel)
                .tag(this)
                .params(Params)
                .execute(new DialogCallback<Object>(getActivity()) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (isOk(response)) {
                            if (!BaseAppLication.getInstance().ispage()) {
                                showToast("取消成功");
                                fReserves.clear();
                                BaseAppLication.getInstance().setIspage(true);
                            }
                            MyHandlerUtil.getHandler().postDelayed(() -> getData(), 200);
                        } else {
                            showError(response);
                        }
                    }
                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }

//
//    //删除预约行程
//    private void Delete(int getid) {
//        OkGo.delete(AppConfig.Deltrip)
//                .tag(this)
//                .params("id",getid)
//                .params("type",1)
//                .execute(new DialogCallback<Object>(getActivity()) {
//                    @Override
//                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
//                        super.onSuccess(response);
//                        if (isOk(response)) {
//                            showToast("删除成功");
//                            if (!BaseAppLication.getInstance().ispage()) {
//                                BaseAppLication.getInstance().setIspage(true);
//                            }MyHandlerUtil.getHandler().postDelayed(() -> loadData(true), 200);
//                        }else {
//                            showError(response);
//                        }
//                    }
//
//                    @Override
//                    public void onError(com.lzy.okgo.model.Response<Object> response) {
//                        super.onError(response);
//                        showError(response);
//                    }
//                });
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==99){
            if (!BaseAppLication.getInstance().ispage()){
                BaseAppLication.getInstance().setIspage(true);
            }
            fReserves.clear();
            getData();
        }
    }


}
